<template>
  <div class="attendance-management" style="width: 100%">
    <!-- 表格头部的自定义内容 -->
    <div class="table-header">
      <el-form
        inline
        style="
          display: flex;
          align-items: center;
          justify-content: flex-start;
          width: 100%;
          margin: 20px 10px 0;
        "
      >
        <el-form-item label="部门" style="flex: 1">
          <el-select
            v-model="searchForm.department"
            placeholder="请选择部门"
            size="medium"
            style="flex: 1; margin-right: 10px"
          >
            <el-option
              v-for="department in departments"
              :key="department.value"
              :label="department.label"
              :value="department.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" style="flex: 1">
          <el-select
            v-model="searchForm.position"
            placeholder="请选择职位"
            size="medium"
            style="flex: 1; margin-right: 10px"
          >
            <el-option
              v-for="position in positions"
              :key="position.value"
              :label="position.label"
              :value="position.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="flex: 1">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="选择日期"
            size="medium"
            style="flex: 1; margin-right: 10px"
          />
        </el-form-item>
        <el-form-item style="display: flex; flex-wrap: nowrap; min-width: 300px">
          <el-button type="default" @click="resetForm" size="medium" style="margin-left: 10px"
            >重置</el-button
          >
          <el-button type="success" @click="clockIn" size="medium" style="margin-left: 10px"
            >一键打卡</el-button
          >
          <el-button type="primary" @click="openAddDialog" size="medium" style="margin-left: 10px"
            >添加考勤</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div v-if="errorVisible" class="error-message">
      <el-alert
        :title="errorMessage"
        type="error"
        center
        show-icon
        @close="errorVisible = false"
      ></el-alert>
    </div>
    <!-- 考勤表格 -->
    <el-table :data="filteredData" style="width: 100%">
      <el-table-column prop="employeeId" label="工号" />
      <el-table-column prop="name" label="员工姓名" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="position" label="职位" />
      <el-table-column prop="date" label="考勤日期" />
      <el-table-column label="考勤状态">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.attendanceStatus)">
            {{ getAttendanceStatus(scope.row.attendanceStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="attendanceStore.pagination.currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="attendanceStore.pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="attendanceStore.total"
    >
    </el-pagination>

    <el-dialog title="编辑考勤信息" v-model="dialogVisible" @close="closeDialog">
      <el-form label-width="120px">
        <el-form-item label="工号">
          <el-input v-model="currentRow.employeeId" readonly></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="currentRow.name" readonly></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="currentRow.department" readonly></el-input>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="currentRow.position" readonly></el-input>
        </el-form-item>
        <el-form-item label="考勤日期">
          <el-input v-model="currentRow.date" readonly></el-input>
        </el-form-item>
        <el-form-item label="考勤状态">
          <el-radio-group v-model="currentRow.attendanceStatus">
            <el-radio
              v-for="status in attendanceStatusOptions"
              :key="status.value"
              :label="status.value"
            >
              {{ status.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveAttendance">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="添加考勤" v-model="addDialogVisible" @close="resetAddForm">
      <el-form label-width="120px">
        <el-form-item label="打卡日期">
          <el-date-picker
            v-model="addForm.date"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="打卡对象">
          <el-radio-group v-model="addForm.object">
            <el-radio :label="'all'">所有人</el-radio>
            <el-radio :label="'department'">该部门</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addForm.object === 'department'" label="打卡部门">
          <el-select v-model="addForm.department" placeholder="请选择部门">
            <el-option
              v-for="department in departments"
              :key="department.value"
              :label="department.label"
              :value="department.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAttendance">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useAttendanceStore } from '@/stores/modules/attendance'
import { updateAttendanceStatus } from '../../api/attendance' // 确保路径正确
import { clockIn as apiClockIn } from '../../api/attendance' // 确保路径正确
import { addAttendance as apiAddAttendance } from '../../api/attendance' // 确保路径正确

const attendanceStore = useAttendanceStore()
const searchForm = reactive({
  department: '',
  position: '',
  startDate: ''
})

const errorVisible = ref(false)
const errorMessage = ref('')
const departments = computed(() => attendanceStore.departments)
const positions = computed(() => attendanceStore.positions)
const attendanceData = computed(() => attendanceStore.attendanceData)
const dialogVisible = ref(false)
const currentRow = ref({})
const attendanceStatusOptions = ref([
  { label: '缺勤', value: 0 },
  { label: '请假', value: 1 },
  { label: '出勤', value: 2 },
  { label: '加班', value: 3 }
])

const addDialogVisible = ref(false)
const addForm = reactive({
  date: '',
  department: '',
  object: 'all' // 'all' 或 'department'
})

// 分页相关响应式数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

onMounted(async () => {
  await attendanceStore.fetchDepartments()
  await attendanceStore.fetchPositions()
  await attendanceStore.fetchAttendanceData()
})

const filteredData = computed(() => {
  const { currentPage, pageSize } = attendanceStore.pagination
  const formattedStartDate = formatDate(searchForm.startDate)
  // 筛选数据
  const filtered = attendanceData.value.filter((item) => {
    return (
      (!searchForm.department || item.department === searchForm.department) &&
      (!searchForm.position || item.position === searchForm.position) &&
      (!formattedStartDate || item.date === formattedStartDate)
    )
  })
  // 更新筛选后的总条数
  attendanceStore.total = filtered.length
  // 返回当前页面的数据
  return filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize)
})

const formatDate = (date) => {
  return date
    ? `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
        .getDate()
        .toString()
        .padStart(2, '0')}`
    : ''
}

const handleSizeChange = (newSize) => {
  attendanceStore.pagination.pageSize = newSize
  attendanceStore.fetchAttendanceData()
}

const handleCurrentChange = (newPage) => {
  attendanceStore.pagination.currentPage = newPage
  attendanceStore.fetchAttendanceData()
}

//c重置
const resetForm = () => {
  searchForm.department = ''
  searchForm.position = ''
  searchForm.startDate = ''
}

// 打卡
const clockIn = async () => {
  // 检查是否选择了部门、职位和日期
  const isDepartmentSelected = searchForm.department !== ''
  const isPositionSelected = searchForm.position !== ''
  const isDateSelected =
    searchForm.startDate !== null &&
    searchForm.startDate !== undefined &&
    searchForm.startDate !== ''

  if (!isDepartmentSelected || !isPositionSelected || !isDateSelected) {
    errorMessage.value = '请完整选择部门、职位和日期进行打卡'
    errorVisible.value = true
    return
  }
  const formattedStartDate = formatDate(searchForm.startDate)
  const clockInIds = attendanceData.value
    .filter(
      (item) =>
        item.department === searchForm.department &&
        item.position === searchForm.position &&
        item.date === formattedStartDate
    )
    .map((item) => item.id) // 收集符合条件的员工的考勤记录ID
  if (clockInIds.length === 0) {
    errorMessage.value = '没有找到符合条件的员工'
    errorVisible.value = true
    return
  }
  try {
    await attendanceStore.performClockIn(clockInIds) // 调用 performClockIn 方法
  } catch (error) {
    errorVisible.value = true
    errorMessage.value = '打卡失败'
    console.error('Error during clock-in:', error)
  }
}

const openDialog = (row) => {
  currentRow.value = {
    employeeId: row.employeeId,
    name: row.name,
    department: row.department,
    position: row.position,
    date: row.date,
    attendanceStatus: row.attendanceStatus
  }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  currentRow.value = {}
}

const saveAttendance = async () => {
  const item = attendanceData.value.find(
    (item) => item.employeeId === currentRow.value.employeeId && item.date === currentRow.value.date
  )

  if (item) {
    await attendanceStore.updateAttendanceStatus(item.id, currentRow.value.attendanceStatus)
    closeDialog()
  } else {
    console.error('未找到对应的考勤记录')
  }
}

const getAttendanceStatus = (status) => {
  switch (status) {
    case 0:
      return '缺勤'
    case 1:
      return '请假'
    case 2:
      return '出勤'
    case 3:
      return '加班'
    default:
      return '未知'
  }
}

const statusTagType = (status) => {
  switch (status) {
    case 0:
      return 'danger'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'info'
    default:
      return ''
  }
}

const openAddDialog = () => {
  addDialogVisible.value = true
}

const resetAddForm = () => {
  addForm.date = ''
  addForm.department = ''
  addForm.object = 'all'
}

const addAttendance = async () => {
  if (!addForm.date) {
    errorMessage.value = '请选择日期'
    errorVisible.value = true
    return
  }

  const selectedDate = formatDate(addForm.date)
  let employees = []

  // 先获取所有在职员工，避免重复添加
  const allActiveEmployees = [
    ...new Set(
      attendanceData.value
        .filter((employee) => employee.status === 1)
        .map((employee) => employee.employeeId)
    )
  ]

  if (addForm.object === 'all') {
    // 如果选择的是所有人，则从所有在职员工中筛选
    employees = allActiveEmployees
  } else {
    // 如果选择的是某个部门，则从该部门的在职员工中筛选
    employees = allActiveEmployees.filter((eid) =>
      attendanceData.value.find(
        (employee) => employee.employeeId === eid && employee.department === addForm.department
      )
    )
  }

  // 移除已经添加了当天考勤记录的员工
  const employeesWithoutCurrentDate = employees.filter((eid) => {
    const existingRecord = attendanceData.value.find(
      (employee) => employee.employeeId === eid && employee.date === selectedDate
    )
    return !existingRecord
  })

  if (employeesWithoutCurrentDate.length === 0) {
    // 数组长度为 0，意味着所有符合条件的员工在所选日期都有考勤记录。
    errorMessage.value = '所选员工在该日期已有考勤记录'
    addDialogVisible.value = false // 关闭对话框
    errorVisible.value = true
    return
  }

  // 构建要添加的考勤记录数组
  const newAttendanceRecords = employeesWithoutCurrentDate.map((eid) => {
    const employee = attendanceData.value.find((employee) => employee.employeeId === eid)
    return {
      date: selectedDate,
      status: 0, // 假设出勤状态码为 2
      eid: eid,
      name: employee.name,
      department: employee.department,
      position: employee.position
    }
  })

  try {
    const response = await apiAddAttendance(newAttendanceRecords)
    if (response.success) {
      addDialogVisible.value = false
      resetAddForm()
      await attendanceStore.fetchAttendanceData()
    } else {
      throw new Error(response.message || '添加考勤失败')
    }
  } catch (error) {
    errorVisible.value = true
    errorMessage.value = error.message || '添加考勤失败'
  }
}
</script>

<style scoped>
.attendance-management {
  padding: 0px;
}
.table-header {
  background-color: #a4cde8; /* 浅蓝色背景 */
  display: flex;
  flex-wrap: nowrap; /* 不换行 */
  justify-content: space-between;
  line-height: 50px;
  overflow: auto; /* 当内容溢出时出现滚动条 */
}
.el-form {
  display: flex;
  flex-wrap: nowrap; /* 不换行 */
}
.text-right {
  text-align: right;
}
</style>